
// Models Sudoku into Exact Cover problem, represented in a DLX grid. 
function SudokuDLX(parameter)
{
	// DLX constructor must be called everytime because of the way "inheritance" works in JavaScript
	this.parentConstructor(729, 324);
	// DancingLink.call(this, 729, 324);

	if (parameter) this.load(parameter)
}
SudokuDLX.prototype = new DancingLink; // inherit all the functions from DancingLink. Parameter is optional since it only copies functions
SudokuDLX.prototype.constructor = SudokuDLX; // re-assign constructor since it has been replaced by the previous line
SudokuDLX.prototype.parentConstructor = DancingLink; // assign DLX constructor to a parentConstructor.

// Load sudoku class into the DLX class.
SudokuDLX.prototype.load = function (load)
{
	for (var r = 0; r < 9; r++)
		for (var c = 0; c < 9; c++)
			this.setCandidate(r, c, load.notations[r][c]);
}

// Fill DLX table using a particular sudoku class.
SudokuDLX.prototype.setCandidate = function (r, c, bitmask)
{
	var HomeRow = r * 81 + c * 9;

	var CellConstraint = r * 9 + c; // cell constraint column
	var RowConstraintHome = 81 + r * 9; // row constraint home column
	var ColConstraintHome = 162 + c * 9; // col constraint home column
	var BoxConstraintHome = 243 + CalcBoxNum(r, c) * 9; // box constraint home column

	while (bitmask)
	{
		RightMostBit = bitmask & ~(bitmask - 1);
		bitmask &= bitmask - 1;
		
		var a = RightMostBit.bitmaskToDigit() - 1;
		var row = HomeRow + a;

		this.set(row, CellConstraint, 1);
		this.set(row, RowConstraintHome + a, 1);
		this.set(row, ColConstraintHome + a, 1);
		this.set(row, BoxConstraintHome + a, 1);
	}
}

SudokuDLX.prototype.solve = function ()
{
	var DLX_Solution = [];

	if (this.algoX(DLX_Solution))
	{
		var Sudoku_Solution = new SudokuGrid();

		for (var i = 0; i < 81; i++) // DLX_Solution.length must be 81
		{
			var ConstraintRow = DLX_Solution[i].row;

			var digit = ConstraintRow % 9 + 1;

			ConstraintRow -= ConstraintRow % 9;
			var col = ConstraintRow % 81 / 9;

			ConstraintRow -= ConstraintRow % 81;
			var row = ConstraintRow / 81;

			Sudoku_Solution.setDigit(row, col, digit);
		}
		return Sudoku_Solution;
	}
	return null;
}
